package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

//创建新的文件
func main() {
	token := "cde937e8f2ef74a72a9807daffe0032d"
	content, _ := ioutil.ReadFile("wblog.db")
	gitRequest := GitRequest{Access_token: token, Content: base64.StdEncoding.EncodeToString(content), Message: "db"}
	requestGiteePost("bzsometest", "git-test", "wblog.db", gitRequest)

}

//更新文件，需要获得上一个文件的sha值
func main2() {
	token := "cde937e8f2ef74a72a9807daffe0032d"
	body := requestGiteeGet(token, "bzsometest", "git-test", "test.txt")
	var dat map[string]interface{}
	if err := json.Unmarshal(body, &dat); err == nil {
		decodeBytes, _ := base64.StdEncoding.DecodeString(dat["content"].(string))
		fmt.Println(string(decodeBytes))
		fmt.Println(dat["sha"])

		gitRequest := GitRequest{Access_token: token, Content: base64.StdEncoding.EncodeToString([]byte("00555")), Sha: dat["sha"].(string), Message: "03"}
		requestGiteePut("bzsometest", "git-test", "test.txt", gitRequest)
	}
}

type GitRequest struct {
	/*注意Json转换必须为公有属性*/
	Access_token string `json:"access_token"`
	Content      string `json:"content"`
	Sha          string `json:"sha"`
	Message      string `json:"message"`
}

func requestGiteeGet(access_token string, owner string, repo string, path string) []byte {
	v := url.Values{}
	v.Add("access_token", access_token)
	encode := v.Encode()
	fmt.Println(encode)
	url := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/contents/%s", owner, repo, path)
	body := request(http.MethodGet, url+"?"+encode, nil, nil)
	return body
}

func requestGiteePut(owner string, repo string, path string, gitRequest GitRequest) {
	url := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/contents/%s", owner, repo, path)
	reqBody, _ := json.Marshal(gitRequest)
	fmt.Println(string(reqBody))
	resBody := request(http.MethodPut, url, nil, reqBody)
	var dat map[string]interface{}
	json.Unmarshal(resBody, &dat)
	fmt.Println(dat)
}
func requestGiteePost(owner string, repo string, path string, gitRequest GitRequest) {
	url := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/contents/%s", owner, repo, path)
	reqBody, _ := json.Marshal(gitRequest)
	resBody := request(http.MethodPost, url, nil, reqBody)
	var dat map[string]interface{}
	json.Unmarshal(resBody, &dat)
	fmt.Println(dat)
}
func request(method string, url string, header map[string]string, body []byte) []byte {
	req, _ := http.NewRequest(method, url, bytes.NewBuffer(body))
	for k, v := range header {
		req.Header.Set(k, v)
	}
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")

	client := &http.Client{}
	resp, _ := client.Do(req)
	body, _ = ioutil.ReadAll(resp.Body)
	return body
}
